import 'package:flutter_frontend/models/user_model.dart';
import 'package:flutter_frontend/pages/mine/upgrade_model.dart';
import 'package:flutter_frontend/utils/app_manager.dart';
import 'package:flutter_frontend/utils/http_manager.dart';
import 'package:package_info_plus/package_info_plus.dart';

class MineApi {
  MineApi._();

  /// 获取个人信息
  static Future<UserInfo?> getUserInfo() async {
    final ApiCallBackInfo info = await HttpManager().requestData('/api/global_service/web/global_user/self_info/');
    if (info.code == 0) return UserInfo.fromJson(info.data);
    return null;
  }

  /// 退出登录
  static void logOut() {
    HttpManager().requestData('/api/global_service/web/area/logout/', httpMethod: HttpMethod.post);
  }

  /// 修改密码
  static Future<String?> changeUserPassword({required String password, required String newPassword, required String confirmNewPassword}) async {
    final Map<String, dynamic> param = {'old_password': password, 'password1': newPassword, 'password2': confirmNewPassword, 'client': 'app'};
    final ApiCallBackInfo info = await HttpManager().requestData('/api/global_service/web/global_user/change_password/', httpMethod: HttpMethod.post, data: param);
    if (info.code == 0) {
      AppManager().setToken(info.data['token']);
      return null;
    }
    return info.message;
  }

  /// 版本更新
  static Future<dynamic> checkAppVersion() async {
    final PackageInfo packageInfo = await PackageInfo.fromPlatform();
    final String packageName = packageInfo.packageName + '.hd';
    final String versionNum = packageInfo.version;
    final int buildNum = int.parse(packageInfo.buildNumber);
    final ApiCallBackInfo info =
        await HttpManager().requestData('/api/global_service/web/area/check_app_upgrade/', queryParameters: {'package': packageName, 'version': versionNum, 'build': buildNum});
    if (info.code == 0) {
      final bool? isUpgrade = info.data['is_upgrade'];
      if (isUpgrade != true) return '当前已是最新版';
      final Map<String, dynamic>? upgradeInfo = info.data['upgrade_info'];
      final String? package = upgradeInfo?['package'];
      if (package != packageName) return '安装包包名错误';
      final String? version = upgradeInfo?['version'];
      if (version == null) return '未配置version号';
      final int? build = upgradeInfo?['build'];
      if (build == null) return '未配置build号';
      if (version == versionNum && build == buildNum) return '当前已是最新版';
      final String? apkName = upgradeInfo?['app_name'];
      final String? url = upgradeInfo?['url'];
      return UpgradeModel()
        ..apkName = apkName == null || apkName.isEmpty ? null : '$apkName.apk'
        ..apkUrl = url;
    }
    return '检查更新失败';
  }
}
